package com.opal.salescost.source;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.HashMap;
import java.util.Map;

@Configuration
@MapperScan(value = {"com.opal.salescost.mapper"},sqlSessionTemplateRef  = "salescostSqlSessionTemplate")
public class SaleDataSource {
    @Resource(name="oracleErpDataSource")
    private DataSource oneDataSource;

    //备用数据源：销售成本明细表模块需要用到
    @Bean("salescostDS")
    public DataSource getDataSource2() throws PropertyVetoException {
        ComboPooledDataSource cpds= new ComboPooledDataSource();
        cpds.setJdbcUrl("jdbc:oracle:thin:@192.168.2.3:1521:orcl");
        cpds.setUser("OPAL202012");
        cpds.setPassword("OPAL202012");
        cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
        return cpds;
    }

    @Bean
    public SalescostSource getDataSource() throws PropertyVetoException {
        //定义map用于封装其它的数据源
        Map<Object, Object> map = new HashMap<>();
        map.put("two", this.getDataSource2());
        SalescostSource dynamicDataSource = new  SalescostSource();
        //封装默认的(主)数据源，若没有提供也就是determineCurrentLookupKey()方法未调用或调用了未找到：使用默认(主)数据源
        dynamicDataSource.setDefaultTargetDataSource(oneDataSource);
        //封装其它数据源
        dynamicDataSource.setTargetDataSources(map);
        return dynamicDataSource;
    }

    //mybatis的sqlSessionFactory
    @Bean("salescostSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean s = new SqlSessionFactoryBean();
        s.setDataSource(this.getDataSource());
        return s.getObject();
    }

    //核心sqlSession的实现类(不创建默认使用DefaultSqlSession实现类)
    @Bean("salescostSqlSessionTemplate")
    public SqlSessionTemplate getSqlSessionTemplate(@Qualifier("salescostSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }

}
